package org.jground.rx.ui.zk;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.rx.IRXObject;
import org.jground.util.CollectionUtils;
import org.zkoss.zul.AbstractListModel;
import org.zkoss.zul.ListModelExt;
import org.zkoss.zul.event.ListDataEvent;

public class UIRXListboxModel extends AbstractListModel implements ListModelExt {
    private static Log logger = LogFactory.getLog(UIRXListboxModel.class);
    private List<IRXObject> list = new ArrayList<IRXObject>();

    public UIRXListboxModel(List<IRXObject> list) {
        this.list = list;
    }

    public Object getElementAt(int index) {
        return list.get(index);
    }

    public int getSize() {
        return list.size();
    }

    public void update() {
        fireEvent(ListDataEvent.CONTENTS_CHANGED, 0, list.size());
    }

    public void removeAll() {
        int size = list.size();
        fireEvent(ListDataEvent.CONTENTS_CHANGED, 0, list.size());
        list.clear();
        fireEvent(ListDataEvent.CONTENTS_CHANGED, 0, size);
    }

    public void addAll(IRXObject[] mods) {
        fireEvent(ListDataEvent.CONTENTS_CHANGED, 0, list.size());
        for (IRXObject mod : mods) {
            CollectionUtils.addUnique(list, mod);
        }
        fireEvent(ListDataEvent.CONTENTS_CHANGED, 0, list.size());
    }

    public void removeObject(IRXObject mod) {
        if (mod == null) {
            return;
        }
        int size = list.size();
        int index = list.indexOf(mod);
        if (index != -1) {
            list.remove(index);
        }
        fireEvent(ListDataEvent.CONTENTS_CHANGED, 0, size);
    }

    public int objectCount() {
        return list.size();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void sort(Comparator cmpr, boolean ascending) {
        Comparator<IRXObject> cmpMod = (Comparator<IRXObject>) cmpr;
        Collections.sort(list, cmpMod);
        fireEvent(ListDataEvent.CONTENTS_CHANGED, 0, list.size());
        logger.debug("sort called");
    }

}
